package de.cbf.cam.dsa.battle.ui.handlers;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.WorkbenchException;
import org.eclipse.ui.handlers.HandlerUtil;

import de.cbf.cam.dice.logic.DiceRoller;
import de.cbf.cam.dsa.battle.ui.dialogs.CombatantChooseDialog;
import de.cbf.cam.dsa.battle.ui.perspectives.BattlePerspective;
import de.cbf.cam.dsa.model.Model;
import de.cbf.cam.dsa.model.ModelBattle;
import de.cbf.cam.dsa.model.entities.BattleChar;
import de.cbf.cam.dsa.model.entities.OneNPC;
import de.cbf.cam.dsa.model.util.Position3f;

/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 * @see org.eclipse.core.commands.IHandler
 * @see org.eclipse.core.commands.AbstractHandler
 */
public class OpenBattleHandler extends AbstractHandler {
	/**
	 * The constructor.
	 */
	public OpenBattleHandler() {
	}

	/**
	 * the command has been executed, so extract extract the needed information
	 * from the application context.
	 */
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
		try {
			//open dialog to choose combatants
			//generate shell
			Shell shell = new Shell(SWT.RESIZE);
			//generate dialog
			CombatantChooseDialog dialog = new CombatantChooseDialog(shell);
			dialog.create();
			//get data
			List<OneNPC> groupCharacters = Model.getInstance().getGroupCharacters();
			List<BattleChar> battleGroupCharacters   = new ArrayList<BattleChar>();
			for(int i = 0; i< groupCharacters.size(); i++ ){
				Position3f position = new Position3f();
				int iniDiceRoll = DiceRoller.rollDice(6);
				BattleChar battleChar = new BattleChar(groupCharacters.get(i), iniDiceRoll, position);
				battleGroupCharacters.add(battleChar);
			}
			
			List<OneNPC>	 possibleCharacters = Model.getInstance().getPossibleCharacters();
			//set dialog data
			dialog.setData(battleGroupCharacters, possibleCharacters);
			dialog.setBlockOnOpen(true);
			//open dialog and get result
			List<BattleChar> battleCharacters = dialog.openForResult();
			if(battleCharacters.size()>0){
				//set result data to model
				ModelBattle.getInstance().setCharactersInBattle(battleCharacters);	
				//open perspective
				window.getWorkbench().showPerspective(BattlePerspective.ID, window);
			}else{
				//no character selected for battle -> no battle -> no opening of perspective
			}
			
		} catch (WorkbenchException e) {			
			e.printStackTrace();
		}
		return null;
	}
}
